package uk.gov.swmprobation.cplitebase;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.osmdroid.api.IMapController;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.GeoPoint;

import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.common.AccountPicker;
import com.uptonweb.barzoomcontrols.BarZoomControl;
import com.uptonweb.barzoomcontrols.BarZoomControl.OnBarZoomListener;

public class CreateProject extends MyActivity {
	
	private MyOpenViewMap myOpenMapView;
	private IMapController myMapController;
	private GeoPoint point;
	private Project project;
	
	static WifiManager wifi;
	BroadcastReceiver receiver;
	ImageView photo;
	RelativeLayout.LayoutParams paramsLeft,paramsRight;
	private int zoom = 19;
	
	private BarZoomControl barzoomcontrol;
	

	final static public String thankYouTitle = "Thank you";
	final static private int thankYouIcon = R.drawable.ic_launcher;
	
	final static private int SEND_NOW = 0;
	final static private int SEND_LATER = 1;
	
	final static private int COMMENT_ID= 12345;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Show Hint each time until setting changed
		setContentView(R.layout.activity_create_project);
		actionBar.hide();
		
		initVariables();

		int max_photo_size = sharedPref.getInt("Max_Picture_Size", 200);
		Bitmap photoBitmap = PhotoTools.fitBitmapIn(project.getImagePath(), max_photo_size);
		if (photoBitmap!=null)	{
			photo.setImageBitmap(photoBitmap);
			photo.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(new File(project.getImagePath())), "image/jpeg");
					startActivity(intent);
				}
    			
    		});
		}
        myOpenMapView.setBuiltInZoomControls(false);
        myOpenMapView.setMultiTouchControls(true);
        if (savedInstanceState!=null){
        	zoom = savedInstanceState.getInt("zoom");
        }
        barzoomcontrol.setCurrentZoom(zoom);
        myMapController.setCenter(point);
        myOpenMapView.allowScroll=true;
        myOpenMapView.allowZoom=true;
        //addMarker();
        TextView licence = (TextView) findViewById(R.id.licence);
        licence.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.map_link)));
				startActivity(browserIntent);				
			}});
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putInt("zoom", zoom);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.application_menu, menu);
        return super.onCreateOptionsMenu(menu);
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
        	easyTracker.send(MapBuilder
	    		      .createEvent("user_action",     // Event category (required)
	    		                   "cancel_create_project",  // Event action (required)
	    		                   "back_button",   // Event label
	    		                   getDuration())            // Event value
	    		      .build()
	    		  );
        }
        return super.onKeyDown(keyCode, event);
    }
	
	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		if (requestCode == SettingsActivity.REQUEST_CODE){
	    if (resultCode == RESULT_OK) {
	        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
	        sharedPref.edit().putString("user_email", accountName).commit();
	        easyTracker.send(MapBuilder
	    		      .createEvent("user_action",     // Event category (required)
	    		                   "email_entry",  // Event action (required)
	    		                   "entered",   // Event label
	    		                   getDuration())            // Event value
	    		      .build()
	    		  );
	        checkWifi();
	    } else {
	    	easyTracker.send(MapBuilder
	    		      .createEvent("user_action",     // Event category (required)
	    		                   "email_entry",  // Event action (required)
	    		                   "not_entered",   // Event label
	    		                   getDuration())            // Event value
	    		      .build()
	    		  );
	    }
		}
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		if(Helper.dialog != null){
			Helper.dialog.dismiss();
		}
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		if (sharedPref.getBoolean(SettingsActivity.submitHintTitle, true)){
			Helper.showHintDialog(this, SettingsActivity.submitHintTitle, SettingsActivity.submitHintMessage, SettingsActivity.submitHintIcon);
		}
		if (sharedPref.getBoolean("left_handed", false)){
			photo.setLayoutParams(paramsRight);
		} else {
			photo.setLayoutParams(paramsLeft);
		}
	}
	
	public void onCross(View view){
		
		final int localId = project.getId();

        Project projectToDelete = DatabaseHandler.getProject(localId);
        
        final String projectName = projectToDelete.getProjectName();
        
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to delete "+projectName+"?");
	    builder.setTitle("Delete project?");
		builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   DatabaseHandler.deleteProject(localId);
		        	   easyTracker.send(MapBuilder
		        	  		      .createEvent("user_action",     // Event category (required)
		        	  		                   "project_action",  // Event action (required)
		        	  		                   "delete",   // Event label
		        	  		                   getDuration())            // Event value
		        	  		      .build()
		        	  		  );
		        	   finish();
		           }
		       });
		builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });

		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	public void onTick(View view){
		if(sharedPref.getString("user_email", "").length()<6){
    		try {
		        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
		                new String[] { "com.google" }, false, null, null, null, null);
		        startActivityForResult(intent, SettingsActivity.REQUEST_CODE);
		    } catch (ActivityNotFoundException e) {
		        // TODO
		    }
    	} else {
    		wantcomment();
    	}
	}
	
	public void onZoomIn(View view){
		myMapController.zoomIn();
	}
	
	public void onZoomOut(View view){
		myMapController.zoomOut();
	}
	
	private void initVariables(){
		Bundle extras = getIntent().getExtras();
		int id = extras.getInt("id");
		project = DatabaseHandler.getProject(id);
		myOpenMapView = (MyOpenViewMap)findViewById(R.id.openmapview);
		
		String tileURL = this.getString(R.string.tileURL);
		final ITileSource tileSource = new XYTileSource(null, null,
	            3, 19, 256, ".png", tileURL);
		myOpenMapView.setTileSource(tileSource);
		
		myMapController = myOpenMapView.getController();
		
		barzoomcontrol = (BarZoomControl) findViewById(R.id.barZoomControls);
		barzoomcontrol.setOnBarZoomListener(new OnBarZoomListener(){

			@Override
			public void OnZoom(int result) {
				zoom=result;
				myMapController.setZoom(zoom);
			}});
		
		myOpenMapView.setMapListener(new MapListener(){

			@Override
			public boolean onScroll(ScrollEvent arg0) {
				return false;
			}

			@Override
			public boolean onZoom(ZoomEvent zoomEvent) {
				barzoomcontrol.setCurrentZoom(zoomEvent.getZoomLevel());
				return false;
			}});
		
        point = new GeoPoint(project.getLat(), project.getLng());
        
        photo = (ImageView) findViewById(R.id.photo);
		paramsLeft= new RelativeLayout.LayoutParams(photo.getLayoutParams());
		paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		paramsLeft.addRule(RelativeLayout.ABOVE,R.id.barZoomControls);
		paramsRight= new RelativeLayout.LayoutParams(photo.getLayoutParams());
		paramsRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		paramsRight.addRule(RelativeLayout.ABOVE,R.id.barZoomControls);
				
	}

	private void wantcomment(){
		if(sharedPref.getBoolean("pref_comment", true)){
			View checkBoxView = View.inflate(this, R.layout.add_comment, null);
			final EditText et = (EditText) checkBoxView.findViewById(R.id.comment);
			final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.savesettingcheck);
			checkBox.setText("Don't ask me to comment again");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Would you like include a comment?");
		    builder.setTitle("Add Comment");
		    builder.setView(checkBoxView);
			builder.setPositiveButton("Send Now", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	try {
			        		project.setProjectComment(URLEncoder.encode(et.getText().toString(),"UTF-8"));
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			        	   if (checkBox.isChecked()){
			        		   sharedPref.edit().putBoolean("pref_comment",false).commit();
			        	   }
			        	   checkWifi();
			           }
			       });

			AlertDialog dialog = builder.create();
			dialog.show();
		} else {
			checkWifi();
		}
	}
	
	private void checkWifi(){
		easyTracker.send(MapBuilder
	  		      .createEvent("user_action",     // Event category (required)
	  		                   "project_action",  // Event action (required)
	  		                   "submit",   // Event label
	  		                   getDuration())            // Event value
	  		      .build()
	  		  );
		PhotoTools.saveThumbnail(project);
		point = (GeoPoint) myOpenMapView.getMapCenter();
		project.setLat(point.getLatitudeE6()/1000000.0);
        project.setLng(point.getLongitudeE6()/1000000.0);
			if(Helper.checkWifi()){
				//If Wifi is available send straight away
				sendNow(project.getId());
			} else {
				//If not send as per users setting
				int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
				switch (wifiCode){
					case 1:
						delaySending();
						break;
					case 2:
						View checkBoxView = View.inflate(this, R.layout.save_setting, null);
						final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.savesettingcheck);
						AlertDialog.Builder builder = new AlertDialog.Builder(this);
						builder.setMessage("Would you like to send now anyway?");
					    builder.setTitle("Wifi not available");
					    builder.setView(checkBoxView);
						builder.setPositiveButton("Send Now", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   if (checkBox.isChecked()){
						        		   sharedPref.edit().putString("pref_wait_wifi","3").commit();
						        	   }
						        	   sendNow(project.getId());
						           }
						       });
						builder.setNegativeButton("Wait for Wifi", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   if (checkBox.isChecked()){
						        		   sharedPref.edit().putString("pref_wait_wifi","1").commit();
						        	   }
						        	   delaySending();
						           }
						       });
	
						AlertDialog dialog = builder.create();
						dialog.show();
						break;
					case 3:
						sendNow(project.getId());
						break;
					default:
						
				}	
			}
	}
	
	private void sendNow(int localId){
		project.setProjectStatus("Waiting");
		project.save();
		Intent serviceIntent = new Intent(this, SendWaiting.class);
		serviceIntent.putExtra("localId", localId);
		this.startService(serviceIntent);
		if (sharedPref.getBoolean(thankYouTitle, true)){
			showThankYou(SEND_NOW);
		} else {
			finish();
		}
	}
	
	private void delaySending(){
		project.setProjectStatus("Waiting");
		project.save();
		if (sharedPref.getBoolean(thankYouTitle, true)){
			showThankYou(SEND_LATER);
		} else {
			finish();
		}
	}
	
	private void showThankYou(int reason){
		AlertDialog dialog;
		View checkBoxView = View.inflate(this, R.layout.save_setting, null);
		final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.savesettingcheck);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String thankYouMessage;
		switch (reason){
		case SEND_NOW:
			thankYouMessage = "We will notify you when the project has been received.";
			break;
		case SEND_LATER:
			thankYouMessage = "Your project will be sent when Wi-Fi becomes available.";
			break;
		default:
			thankYouMessage = "We will notify you when the project has been received.";
		}
		builder.setMessage(thankYouMessage);
	    builder.setTitle(thankYouTitle);
	    builder.setIcon(thankYouIcon);
	    builder.setView(checkBoxView);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   if (checkBox.isChecked()){
		        		   sharedPref.edit().putBoolean(thankYouTitle, false).commit();
		        	   }
		        	   finish();
		           }
		       });

		dialog = builder.create();
		dialog.show();
	}
}
